<script>
import { dayjs } from 'element-plus';
let MyChart = null;
function getRandomData(min, max, acc) {
  return Number(parseFloat((max - min) * Math.random() + min).toFixed(acc || 0))
}
function RenderChart(names, values) {
  if (MyChart) {
    MyChart.dispose();
    MyChart = null;
  }
  MyChart = echarts.init(document.getElementById('Echart-area-monotor2'));
  let bgColor = "#fff";
  let color = [
    "#5189F8",
    "#8bc34a",
    "#ffc107",
    "#673ab7",
    "#ff5722",
  ];

  let xAxisData = names;
  const hexToRgba = (hex, opacity) => {
    let rgbaColor = "";
    let reg = /^#[\da-f]{6}$/i;
    if (reg.test(hex)) {
      rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
        "0x" + hex.slice(3, 5)
      )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
    }
    return rgbaColor;
  }

  const option = {
    backgroundColor: bgColor,
    color: color,
    legend: {
      show: true,
      textStyle: {
        fontSize: '14',
        color: '#000',
        fontFamily: 'ALIBABAPUHUI-REGU'
      }
    },
    tooltip: {
    },
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {
          show: true,
          title: "导出当前图片",
          excludeComponents: ["toolbox"],
          pixelRatio: 1,
          backgroundColor: "#05233D",
        },
      },
    },
    grid: {
      top: 50,
      right: 50,
      bottom: 30,
      left: 20,
      containLabel: true
    },
    dataZoom: {
      type: 'slider',
      start: 30,
      end: 80
    },
    xAxis: [{
      type: "category",
      boundaryGap: false,
      axisLabel: {
        formatter: '{value}',
        textStyle: {
          fontFamily: 'ALIBABAPUHUI-REGU',
          color: "#333"
        }
      },
      axisLine: {
        lineStyle: {
          color: "#D9D9D9"
        }
      },
      data: xAxisData
    }],
    yAxis: [{
      type: "value",
      name: '温度: ℃',
      axisLabel: {
        textStyle: {
          fontFamily: 'ALIBABAPUHUI-REGU',
          color: "#666"
        }
      },
      nameTextStyle: {
        color: "#666",
        fontFamily: 'ALIBABAPUHUI-REGU',
        fontSize: 12,
        lineHeight: 40
      },
      splitLine: {
        lineStyle: {
          type: "dashed",
          color: "#E9E9E9"
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    }],
    series: values.map((v, index) => {
      return {
        name: v[0].name,
        type: "line",
        smooth: true,
        symbolSize: 8,
        zlevel: 3,
        lineStyle: {
          normal: {
            color: color[index],
            shadowBlur: 3,
            shadowColor: hexToRgba(color[index], 0.5),
            shadowOffsetY: 8
          }
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [{
                offset: 0,
                color: hexToRgba(color[index], 0.3)
              },
              {
                offset: 1,
                color: hexToRgba(color[index], 0.1)
              }
              ],
              false
            ),
            shadowColor: hexToRgba(color[index], 0.1),
            shadowBlur: 10
          }
        },
        label: {
          show: false,
          position: 'top',
          fontWeight: 'bold',
        },
        data: v
      }
    })
  };
  MyChart.setOption(option);
}
let ObjMap = Object.create(null);
const originSize = 15;
export default {
  name: "monitor2",
  components: {
  },
  data() {
    return {
      loadingSVG: `
        <circle class="path" cx="25" cy="25" r="10" fill="none">
        </circle>
      `,
      // 正在上传
      isUploading: false,
      // 正在导出
      isExporting: false,
      originSize: originSize,
      tableData: [],
      formData: {
        size: originSize,
        updateTime: dayjs().format('YYYY/MM/DD'),
      },
      radio: 'day',
      datePickerRange: [
        dayjs().subtract(90, 'day').format('YYYY/MM/DD'),
        dayjs().format('YYYY/MM/DD')
      ],
      datePickerRange2: [
        dayjs().subtract(3, 'day').format('YYYY/MM/DD 00:00:00'),
        dayjs().format('YYYY/MM/DD 00:00:00')
      ],
      cascaderValue: [],
      cascaderProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          if (level === 0) {
            Api.getDataOfGRZ({
              ids: [],
              // 单位名称
              fields: ['SMID', 'DWMC'],
              attributeFilter: ''
            }).then(res => {
              this.listData = [];
              const obj = Object.create(null);
              if (!res.features || !res.features.length) { resolve([]) }
              res.features.forEach(v => {
                const pro = v.properties;
                const DWMC = pro.DWMC
                if (!obj[DWMC]) {
                  obj[DWMC] = 1;
                } else {
                  obj[DWMC]++
                }
              });
              const listData = [];
              Object.keys(obj).forEach(v => {
                listData.push({
                  label: v,
                  value: v
                })
                ObjMap[v] = v;
              })
              resolve(listData)
            })
          } else if (level === 1) {
            Api.getDataOfGRZ({
              ids: [],
              // 站点名称 热源主键编码
              // fields: ['SMID', 'HRZBM', 'ZDMC', 'ZJBM', 'DWMC', 'RYDZ', 'FZR', 'LXFS', 'HRZ_COUNT'],
              fields: ['ZDMC', 'ZJBM'],
              attributeFilter: 'DWMC=' + '\'' + node.value + '\''
            }).then(res => {
              const listData = [];
              if (!res.features || !res.features.length) { resolve([]) }
              res.features.forEach(v => {
                const pro = v.properties;
                listData.push({
                  label: pro.ZDMC,
                  value: pro.ZJBM
                })
                ObjMap[pro.ZJBM] = pro.ZDMC;
              });
              resolve(listData)
            })
          } else if (level === 2) {
            Api.getDataOfHRZ({
              ids: [],
              // // 换热站名称 热源主键编码
              // fields: ['SMID', 'HRZMC', 'ZJBM', 'GRZZJBM', 'RYMC', 'ZDMC', 'XQ_COUNT', 'SFZG'],
              fields: ['HRZMC', 'ZJBM'],
              attributeFilter: 'GRZZJBM=' + '\'' + node.value + '\''
            }).then(res => {
              const listData = [];
              if (!res.features || !res.features.length) { resolve([]) }
              res.features.forEach(v => {
                const pro = v.properties;
                listData.push({
                  label: pro.HRZMC,
                  value: pro.ZJBM,
                  leaf: true
                })
                ObjMap[pro.ZJBM] = pro.HRZMC
              });
              resolve(listData)
            })
          } else {
            resolve([])
          }
        },
      },
      mainPosition: '',
      minValue1: '100',
      minValue2: '100',
      minValue3: '100',
      minValue4: '100',
      maxValue1: '100',
      maxValue2: '100',
      maxValue3: '100',
      maxValue4: '100',
    };
  },
  computed: {
    mainStyle() {
      let maxHeight = (window.innerHeight / window.dpr - 400) / 2;
      return {
        height: maxHeight + 'px'
      }
    },
  },
  watch: {
    cascaderValue(nV, oV) {
      // console.log(nV, 'nV')
    },
    radio(nV, oV) {
      this.reset()
    }
  },
  mounted() {
    // this.defaultValueRange = [
    //   new Date(dayjs().subtract(1, 'day').format('YYYY/MM/DD')),
    //   new Date(dayjs().format('YYYY/MM/DD'))
    // ]
    this.doSearch()
  },
  beforeUnmount() {
    if (MyChart) {
      MyChart.dispose();
      MyChart = null;
    }
  },
  methods: {
    //  查询
    doSearch() {
      let totalSize = 0;
      const res = [];
      const idSeed = new Date().getTime()
      let head = null;
      let formatS = ''
      if (this.radio === 'day') {
        // 定义两个日期
        const startDate = dayjs(this.datePickerRange[0], 'YYYY/MM/DD');
        const endDate = dayjs(this.datePickerRange[1], 'YYYY/MM/DD');

        // 计算日期之间的天数差
        const daysDiff = endDate.diff(startDate, 'day');
        totalSize = daysDiff;
        head = this.datePickerRange[0]
        formatS = 'YYYY/MM/DD'
      } else {
        // 定义两个日期
        const startDate = dayjs(this.datePickerRange2[0], 'YYYY/MM/DD');
        const endDate = dayjs(this.datePickerRange2[1], 'YYYY/MM/DD');

        // 计算日期之间的天数差
        const daysDiff = endDate.diff(startDate, 'hour');
        totalSize = daysDiff;
        head = this.datePickerRange2[0]

        formatS = 'YYYY/MM/DD HH:mm'
      }
      let name = '青岛家盛热力公司';
      let stationName = '渤海湾';
      if (this.cascaderValue && this.cascaderValue.length) {
        name = ObjMap[this.cascaderValue[0]];
        stationName = ObjMap[this.cascaderValue[2]];
      }
      this.mainPosition = stationName;

      for (let i = 0; i < totalSize; i++) {
        const item = {
          id: String(idSeed + i),
          name: name,
          stationName: stationName,
          generateTime: dayjs(head).add(i, this.radio).format(formatS),
          onceProvideTemp: getRandomData(55, 60, 1),
          twiceProvideTemp: getRandomData(35, 33, 1),
          onceBackTemp: getRandomData(33, 30, 1),
          twiceBackTemp: getRandomData(30, 28, 1),
        }
        res.push(item)
      }
      this.tableData = res;
      this.minValue1 = Math.min.apply(null, this.tableData.map(v => { return v.onceProvideTemp }))
      this.maxValue1 = Math.max.apply(null, this.tableData.map(v => { return v.onceProvideTemp }))

      this.minValue2 = Math.min.apply(null, this.tableData.map(v => { return v.twiceProvideTemp }))
      this.maxValue2 = Math.max.apply(null, this.tableData.map(v => { return v.twiceProvideTemp }))

      this.minValue3 = Math.min.apply(null, this.tableData.map(v => { return v.onceBackTemp }))
      this.maxValue3 = Math.max.apply(null, this.tableData.map(v => { return v.onceBackTemp }))

      this.minValue4 = Math.min.apply(null, this.tableData.map(v => { return v.twiceBackTemp }))
      this.maxValue4 = Math.max.apply(null, this.tableData.map(v => { return v.twiceBackTemp }))

      RenderChart(this.tableData.map(v => {
        return v.generateTime
      }), [this.tableData.map(v => {
        return {
          name: '一供（平均）温度',
          value: v.onceProvideTemp
        }
      }), this.tableData.map(v => {
        return {
          name: '二供（平均）温度',
          value: v.twiceProvideTemp
        }
      }), this.tableData.map(v => {
        return {
          name: '一回（平均）温度',
          value: v.onceBackTemp
        }
      }), this.tableData.map(v => {
        return {
          name: '二回（平均）温度',
          value: v.twiceBackTemp
        }
      })])
      // console.log(this.tableData, 'this.tableData')
    },
    //  重置
    reset() {
      // this.formData.ssgs = '';
      // this.formData.ssxq = '';
      // this.formData.wtfl = '';
      // this.formData.page = 1;
      // this.formData.size = this.originSize;
      // this.formData.updateTime = dayjs().format('YYYY/MM/DD')
      this.datePickerRange = [
        dayjs().subtract(90, 'day').format('YYYY/MM/DD'),
        dayjs().format('YYYY/MM/DD')
      ]
      this.datePickerRange2 = [
        dayjs().subtract(3, 'day').format('YYYY/MM/DD 00:00:00'),
        dayjs().format('YYYY/MM/DD 00:00:00')
      ]
      this.doSearch();
    },
    download() {
      if (!XLSX) { return }
      // 定义JSON数据
      const jsonData = this.tableData;

      // 自定义表头
      const header = [[
        '编号',
        '公司名称',
        '站点名称',
        '记录时间',
        '一供温度',
        '二供温度',
        '一回温度',
        '二回温度']];

      // 将表头转换为工作表
      const headerWs = XLSX.utils.aoa_to_sheet(header);

      // 将JSON数据添加到工作表中，跳过表头
      const ws = XLSX.utils.sheet_add_json(headerWs, jsonData, { skipHeader: true, origin: -1 });

      // 创建一个新的工作簿
      const workbook = XLSX.utils.book_new();

      // 将工作表添加到工作簿中
      XLSX.utils.book_append_sheet(workbook, ws, "Sheet1");

      let start = '';
      let end = '';
      if (this.radio === 'day') {
        start = dayjs(this.datePickerRange[0]).format('YYYY/MM/DD')
        end = dayjs(this.datePickerRange[1]).format('YYYY/MM/DD')
      } else {
        start = dayjs(this.datePickerRange2[0]).format('YYYY/MM/DD HH:mm:SS')
        end = dayjs(this.datePickerRange2[1]).format('YYYY/MM/DD HH:mm:SS')
      }
      // 导出Excel文件
      XLSX.writeFile(workbook, `${start}-${end}数据导出.xlsx`);
    }
  },
};
</script>

<template>
  <!-- layout 外包层 -->
  <div class="monitor2 full-height">
    <div class="titles-area">
      <div class="main-title font-alimamashuheiti">
        监测报表
      </div>
      <div class="sub-title font-AlibabaPuhui">
        自定义查询各个指标的运行状况
      </div>
    </div>
    <div class="search-area">
      <el-row :gutter="10">
        <el-col :span="16">
          <el-row>
            <el-col :span="5">
              <el-row>
                <el-col :span="12" class="inline-flex-self">
                  <el-text class="mx-1">时段：</el-text>
                </el-col>
                <el-col :span="12">
                  <el-radio-group style="margin-right: 1rem;" v-model="radio">
                    <el-radio-button label="天" value="day" />
                    <el-radio-button label="小时" value="hour" />
                  </el-radio-group>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6" class="inline-flex-self">
              <el-row>
                <el-col :span="24">
                  <el-date-picker v-if="radio === 'day'" style="width: calc(100% - 20px);" v-model="datePickerRange"
                    type="daterange" value-format="YYYY/MM/DD" start-placeholder="开始日期" end-placeholder="结束日期" />
                  <el-date-picker v-if="radio === 'hour'" style="width: calc(100% - 20px);" v-model="datePickerRange2"
                    type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY/MM/DD HH:mm:ss"
                    date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6">
              <el-row>
                <el-col :span="8" class="inline-flex-self">
                  <el-text class="mx-1">公司/站点：</el-text>
                </el-col>
                <el-col :span="16">
                  <el-cascader v-model="cascaderValue" :props="cascaderProps" :show-all-levels="false" clearable
                    placeholder="请选择公司或者站点" />
                </el-col>
              </el-row>
            </el-col>
          </el-row>

        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="() => {
            doSearch()
          }">查询</el-button>
          <el-button type="info" @click="() => {
            reset()
          }">重置</el-button>
          <el-button type="info" @click="() => {
            download()
          }">导出</el-button>
        </el-col>


        <!-- <el-col :span="2">
          <el-select placeholder="请选择投诉类型" v-model="formData.wtfl" clearable @change="changeType">
            <el-option value="供暖不热" label="供暖不热"></el-option>
            <el-option value="申请供热服务" label="申请供热服务"></el-option>
            <el-option value="收费退费欠费赔偿等问题" label="收费退费欠费赔偿等问题"></el-option>
            <el-option value="供热设施维修" label="供热设施维修"></el-option>
            <el-option value="非市政集中供热问题" label="非市政集中供热问题"></el-option>
            <el-option value="其它问题" label="其它问题"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-date-picker style="width: 100%" v-model="formData.updateTime" type="date" placeholder="请选择更新时间"
            format="YYYY/MM/DD" value-format="YYYY/MM/DD">
          </el-date-picker>
        </el-col> -->

      </el-row>
    </div>
    <div class="list-area">
      <el-table :data="tableData" :style="mainStyle" border stripe @selection-change="handleSelectionChange"
        row-key="id" empty-text="暂无数据" :default-sort="{ prop: 'ssgs', order: 'descending' }">
        <!--        <el-table-column header-align="center" align="center" type="selection"  width="60" />-->
        <el-table-column header-align="center" type="index" label="序号" align="center" width="70" />
        <el-table-column header-align="center" align="center" prop="name" label="公司名称" sortable />
        <el-table-column header-align="center" align="center" prop="stationName" label="站点名称" sortable />
        <el-table-column header-align="center" align="center" prop="generateTime" label="记录时间" sortable />
        <el-table-column header-align="center" align="center" prop="onceProvideTemp" label="一供温度" width="180"
          sortable />
        <el-table-column header-align="center" align="center" prop="twiceProvideTemp" label="二供温度" width="180"
          sortable />
        <el-table-column header-align="center" align="center" prop="onceBackTemp" label="一回温度" width="180" sortable />
        <el-table-column header-align="center" align="center" prop="twiceBackTemp" label="二回温度" width="180" sortable />
        <!-- <el-table-column header-align="center" align="center" fixed="right" label="操作" width="150">
          <template #header>
            <span style="display: inline-flex; align-items: center">
              操作
              <el-tooltip effect="light" placement="top-start" content="撤销操作将已经导出 WORD 的投诉表回退到未导出状态">
                <el-icon>
                  <infoFilled />
                </el-icon>
              </el-tooltip>

            </span>
          </template>
<template #default="scope">
            <el-button link type="info" size="small" @click="(e) => { currentRow = scope.row; dialogVisible = true; }">
              撤销
            </el-button>
            <el-button link type="primary" size="small"
              @click="(e) => { currentRow = scope.row; dialogVisibleDetail = true; }">
              查看详情
            </el-button>
          </template>
</el-table-column> -->
      </el-table>
    </div>
    <div class="description-item">
      <span>监测点：</span>
      <span>{{ mainPosition }}</span>
      <span>（</span>
      <span>最小值：</span>
      <span class="color-1" title="一供最低温度">{{ minValue1 }}</span>
      <span class="color-2" title="二供最低温度">{{ minValue2 }}</span>
      <span class="color-3" title="一回最低温度">{{ minValue3 }}</span>
      <span class="color-4" title="二回最低温度">{{ minValue4 }}</span>
      <span>最大值：</span>
      <span class="color-1" title="一供最高温度">{{ maxValue1 }}</span>
      <span class="color-2" title="二供最高温度">{{ maxValue2 }}</span>
      <span class="color-3" title="一回最高温度">{{ maxValue3 }}</span>
      <span class="color-4" title="二回最高温度">{{ maxValue4 }}</span>
      <span>）</span>
    </div>

    <div id="Echart-area-monotor2">

    </div>
  </div>
</template>
<style></style>
<style lang="less">
.monitor2 {

  &>.list-area {
    height: calc(50% - 12rem);

    &>.page-area {
      height: 50px;
    }
  }
}

.description-item {
  height: 3rem;
  line-height: 3rem;
  font-size: 1.5rem;
  color: #333;
  &>.color-1 {
    color: #5189F8;
  }
  &>.color-2 {
    color: #8bc34a;
  }
  &>.color-3 {
    color: #ffc107;
  }
  &>.color-4 {
    color: #673ab7;
  }
  &> span[class^="color"]{
    margin-right: 5px;
  }
}

#Echart-area-monotor2 {
  // margin-top: 2rem;
  height: calc(50% - 5rem);
}

.search-area {
  margin-bottom: 1rem;
}

.page-area {
  padding-right: 1rem;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #fff;
}

.titles-area {
  &>.main-title {
    font-size: 2rem;
    line-height: 2;
  }

  &>.sub-title {
    font-size: 1.4rem;
    color: #9e9e9e;
    line-height: 2;
  }
}
</style>
